package com.wfs.myapp.service.impl;

import com.wfs.myapp.common.ApiResult;
import com.wfs.myapp.entity.domain.User;
import com.wfs.myapp.entity.domain.bk.BkBook;
import com.wfs.myapp.entity.dto.req.bk.AddBookReqDto;
import com.wfs.myapp.entity.vo.BkBookVo;
import com.wfs.myapp.entity.vo.PageResponse;
import com.wfs.myapp.enums.BookStatusEnum;
import com.wfs.myapp.enums.ResponseCodeEnum;
import com.wfs.myapp.repository.UserRepository;
import com.wfs.myapp.repository.bk.BookRepository;
import com.wfs.myapp.service.BkBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
@Slf4j
public class BkBookServiceImpl implements BkBookService {

    @Autowired
    private BookRepository bookRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult<?> addOrUpdate(Long userId, AddBookReqDto addGroupReqDto) {
        BkBook book;
        if (Objects.nonNull(addGroupReqDto.getId())) {
            // 修改
            Optional<BkBook> byId = bookRepository.findById(addGroupReqDto.getId());
            if (!byId.isPresent()) return ApiResult.error(ResponseCodeEnum.BOOK_NOT_EXIST);
            book = byId.get();
            BeanUtils.copyProperties(addGroupReqDto, book);
            book.setUpdatedTime(LocalDateTime.now());
            book.setUpdatedBy(String.valueOf(userId));
        } else {
            // 添加组
            book = new BkBook();
            BeanUtils.copyProperties(addGroupReqDto, book);
            book.setUserId(userId);
            book.setStatus(BookStatusEnum.PENDING.getCode());
            book.setCreatedBy(String.valueOf(userId));
            book.setUpdatedBy(String.valueOf(userId));
        }
        book = bookRepository.save(book);
        return ApiResult.success(book);
    }


    @Override
    public ApiResult<?> myBookList(Long userId, Integer page, Integer size) {
        long total = bookRepository.countByUserId(userId);
        if (total == 0) return ApiResult.success(new PageResponse(new ArrayList(), total, page, size));
        List<BkBook> bookList = bookRepository.findByUserId(userId, (page-1)*size, size);
        return ApiResult.success(new PageResponse(bookList, total, page, size));
    }

    @Override
    public ApiResult<BkBookVo> bookInfo(Long id) {
        BkBookVo bkBookVo = new BkBookVo();
        Optional<BkBook> bookOpt = bookRepository.findById(id);
        if (!bookOpt.isPresent()) return ApiResult.error(ResponseCodeEnum.BOOK_NOT_EXIST);
        BkBook book = bookOpt.get();
        BeanUtils.copyProperties(bookOpt, bkBookVo);
        bkBookVo.setId(book.getId());
        bkBookVo.setBookName(book.getBookName());
        bkBookVo.setBookAvatar(book.getBookAvatar());
        bkBookVo.setAuthor(book.getAuthor());
        bkBookVo.setUserId(book.getUserId());
        bkBookVo.setDescription(book.getDescription());
        bkBookVo.setStatus(book.getStatus());
        bkBookVo.setStatusStr(BookStatusEnum.getMsg(book.getStatus()));
        Optional<User> userOpt = userRepository.findById(book.getUserId());
        if (!userOpt.isPresent()) return ApiResult.error(ResponseCodeEnum.USER_NOT_EXIST);
        User user = userOpt.get();
        bkBookVo.setUserName(user.getNickname());
        bkBookVo.setUserAvatar(user.getAvatar());
        return ApiResult.success(bkBookVo);
    }

    @Override
    public ApiResult<?> bookListByUserId(Long userId) {
        List<BkBookVo> list = new ArrayList<>();
        List<BkBook> allByUserId = bookRepository.findAllByUserId(userId);
        for (BkBook book : allByUserId) {
            BkBookVo bkBookVo = new BkBookVo();
            BeanUtils.copyProperties(book, bkBookVo);
            bkBookVo.setStatusStr(BookStatusEnum.getMsg(book.getStatus()));
            list.add(bkBookVo);
        }
        return ApiResult.success(list);
    }

    @Override
    public ApiResult<?> myPendingBookList(Long userId, Integer page, Integer size) {
        long total = bookRepository.countPendingBookByUserId(userId);
        if (total == 0) return ApiResult.success(new PageResponse(new ArrayList(), total, page, size));
        List<BkBook> bookList = bookRepository.findPendingBookByUserId(userId, (page-1)*size, size);
        return ApiResult.success(new PageResponse(bookList, total, page, size));
    }

}
